package com.song.common.handler.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.song.common.result.ResultEntity;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        ResultEntity resultEntity = ResultEntity.failMessage("流控异常");
        if (e instanceof FlowException){
            resultEntity = ResultEntity.failMessage("流控异常");
        }else if (e instanceof ParamFlowException){
            resultEntity = ResultEntity.failMessage("热点参数异常");
        }else if (e instanceof DegradeException){
            resultEntity = ResultEntity.failMessage("降级异常");
        }else if (e instanceof AuthorityException){
            resultEntity = ResultEntity.failMessage("授权异常");
        }else if (e instanceof SystemBlockException){
            resultEntity = ResultEntity.failMessage("系统自适应异常");
        }
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), resultEntity);
    }
}
